package cn.icare.cms.impl;

import cn.icare.cms.ListUtil;
import cn.icare.cms.PromotionService;
import cn.icare.cms.StringUtil;
import cn.icare.cms.dao.mapper.CustomMapper;
import cn.icare.cms.dao.mapper.ItemMapper;
import cn.icare.cms.dao.mapper.PromotionItemMapper;
import cn.icare.cms.dao.mapper.PromotionMapper;
import cn.icare.cms.dao.po.Item;
import cn.icare.cms.dao.po.Promotion;
import cn.icare.cms.dao.po.PromotionItem;
import cn.icare.cms.model.enums.ItemStatusEnum;
import cn.icare.cms.model.ro.AddPromotionRO;
import cn.icare.cms.model.ro.EditPromotionRO;
import cn.icare.cms.model.ro.SavePromotionItemRo;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PromotionServiceImpl implements PromotionService {

    private final Logger logger = LoggerFactory.getLogger(PromotionServiceImpl.class);

    @Resource
    private PromotionMapper promotionMapper;

    @Resource
    private PromotionItemMapper promotionItemMapper;

    @Resource
    private ItemMapper itemMapper;

    @Resource
    private CustomMapper customMapper;

    @Override
    public Integer createOne(AddPromotionRO ro, String actionUserName) {
        try {
            Promotion promotion = new Promotion();
            promotion.setKind(ro.getKind());
            promotion.setType(ro.getType());
            promotion.setTitle(ro.getTitle());
            promotion.setRate(ro.getRate());
            promotion.setMarkdownnum(ro.getMarkdownnum());
            promotion.setNeeddownnum(ro.getNeeddownnum());
            promotion.setStarttime(ro.getStarttime());
            promotion.setEndtime(ro.getEndtime());
            promotion.setCreator(actionUserName);
            promotion.setCreatetime(new Date());
            int result = promotionMapper.insertSelective(promotion);
            if (result > 0) {
                int promId = promotion.getId();
                return promId;
            }
        } catch (Exception e) {
            this.logger.error("createOne 异常", e);
        }
        return 0;
    }

    @Override
    public boolean updateOne(EditPromotionRO ro, String actionUserName) {
        boolean isSuccess = false;
        try {
            Promotion promotion = new Promotion();
            promotion.setId(ro.getId());
            promotion.setTitle(ro.getTitle());
            promotion.setType(ro.getType());
            promotion.setRate(ro.getRate());
            promotion.setMarkdownnum(ro.getMarkdownnum());
            promotion.setNeeddownnum(ro.getNeeddownnum());
            promotion.setStarttime(ro.getStarttime());
            promotion.setEndtime(ro.getEndtime());
            promotion.setCreatetime(new Date());
            promotion.setCreator(actionUserName);
            int result = promotionMapper.updateByPrimaryKeySelective(promotion);
            if (result > 0) {
                isSuccess = true;

            }
        } catch (Exception e) {
            this.logger.error("createOne 异常", e);
        }

        return isSuccess;
    }

    @Override
    public boolean deleteOne(Integer id) {

        return this.promotionMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public boolean deleteBatch(List<Integer> ids) {
        boolean result = false;
        try {
            if (ListUtil.isNotEmpty(ids)) {
                Example example = new Example(Promotion.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn("id", ids);
                result = this.promotionMapper.deleteByExample(example) > 0;
            }
        } catch (Exception e) {
            this.logger.error("deleteBatch 异常", e);

        }
        return result;
    }

    @Override
    public Promotion getOne(Integer id) {
        return this.promotionMapper.selectByPrimaryKey(id);
    }

    @Override
    public MsgDatasVO getList(Integer kind, Integer type, String title, Integer pageNum, Integer pageSize) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            PageHelper.startPage(pageNum, pageSize);
            Example example = new Example(Promotion.class);
            Example.Criteria criteria = example.createCriteria();
            if (kind!=null && kind > 0) {
                criteria.andEqualTo("kind", kind);
            }
            if (type!=null && type > 0) {
                criteria.andEqualTo("type", type);
            }
            if (StringUtil.isNotEmpty(title)) {
                criteria.andLike("title", "%" + title + "%");
            }
            List<Promotion> dataList = this.promotionMapper.selectByExample(example);
            PageInfo pageInfo = new PageInfo(dataList);
            result.setTotal(pageInfo.getTotal());
            result.setDatas(dataList);

        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public boolean exists(Integer id, String title) {

        Example example = new Example(Promotion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("title", title);
        criteria.andNotEqualTo("id",id);
        int result = this.promotionMapper.selectCountByExample(example);
        return result > 0;
    }

    @Override
    public MsgDatasVO getNoPromItemList(Long cid, String title, Integer pageNum, Integer pageSize) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            PageHelper.startPage(pageNum, pageSize);
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            if (cid != null && cid > 0) {
                criteria.andEqualTo("cid", cid);
            }
            if (StringUtil.isNotEmpty(title)) {
                criteria.andLike("title", "%" + title + "%");
            }
            //只查询商品状态为正常
            criteria.andEqualTo("status", ItemStatusEnum.NORMAL.getCode());
            criteria.andCondition("id not in (\n" +
                    "SELECT b.itemid from t_promotion a,t_promotion_item b where a.id=b.promid and  a.endtime>NOW()\n" +
                    ")");
            List<Item> dataList=this.itemMapper.selectByExample(example);
            PageInfo pageInfo = new PageInfo(dataList);
            result.setTotal(pageInfo.getTotal());
            result.setDatas(dataList);

        }catch (Exception ex)
        {
            logger.error("getNoPromItemList 异常",ex);
        }
        return result;
    }

    @Override
    public MsgDatasVO getPromItemList(Integer promId, String title) {

        MsgDatasVO result = new MsgDatasVO();
        try {
            String sql = "select a.itemid,b.title,b.price oldprice,a.price price,ifnull(a.num,0) num from t_promotion_item a,t_item b where a.itemid=b.id";
            if (promId != null && promId > 0) {
                sql += " and a.promid=" + promId;
            }

            if (StringUtil.isNotEmpty(title)) {
                sql += " and b.title like '%" + title + "%'";
            }
            List<Map<String, Object>> dataList = customMapper.select(sql);
            result.setDatas(dataList);
            result.setTotal(dataList.size());
        }
        catch (Exception ex)
        {
            this.logger.error("getPromItemList 异常",ex);
        }
        return result;
    }

    public boolean savePromotionItem(Integer promId, List<SavePromotionItemRo> itemList) {
      boolean result=true;
       try {
           Example example = new Example(PromotionItem.class);
           Example.Criteria criteria = example.createCriteria();
           criteria.andEqualTo("promid", promId);
           this.promotionItemMapper.deleteByExample(example);
           PromotionItem promotionItem;
           for (SavePromotionItemRo item : itemList) {
               promotionItem = new PromotionItem();
               promotionItem.setItemid(item.getItemid());
               promotionItem.setPromid(promId);
               promotionItem.setNum(item.getNum());
               promotionItem.setPrice(item.getPrice());
               this.promotionItemMapper.insertSelective(promotionItem);
           }
           result=true;
       }catch (Exception ex)
       {
           this.logger.error("savePromotionItem 异常",ex);
       }
       return result;

    }

    @Override
    public MsgDatasVO getMiniEffectiveList() {

        MsgDatasVO result = new MsgDatasVO();
        try {
            Example example = new Example(Promotion.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andGreaterThanOrEqualTo("endtime",new Date());
            criteria.andLessThanOrEqualTo("starttime",new Date());
            example.selectProperties("id","title","starttime","endtime");
            example.setOrderByClause("starttime");
            List<Promotion> dataList=this.promotionMapper.selectByExample(example);
            result.setTotal(dataList.size());
            result.setDatas(dataList);
        }
        catch (Exception ex)
        {
            this.logger.error("getMiniEffectiveList 异常",ex);
        }
        return result;
    }

    @Override
    public boolean subtractItemNum(Long itemId, Integer promId, Integer num) {
        String sql=String.format("update t_promotion_item set num=num-%s where itemid=%s and promid=%s and num>=%s",
                num,itemId,promId,num);
        return this.customMapper.update(sql)>0;
    }

    @Override
    public boolean addItemNum(Long itemId, Integer promId, Integer num) {
        String sql=String.format("update t_promotion_item set num=num+%s where itemid=%s and promid=%s",
                num,itemId,promId);
        return this.customMapper.update(sql)>0;
    }
}
